package sve.generator;

import java.util.ArrayList;

import cmdp.HierarchicalParser;
import cmdp.TokenStream;
import sve.SVE;
import sve.Utils;

import xadd.XADD;

public class RoboticsGen {

	public static void generate(int count) {
		String str = "";
		XADD x = new XADD();
		TokenStream t = new TokenStream();
		int[] ids = new int[3];
		ArrayList a;
		int id;

		// t.read("( [d > 0.0] ( [d < 10.0] ( [0.1] ) ( [0.0] ) ) ( [0.0] ) ) ");
		// ArrayList a = HierarchicalParser.ParseFileInt(t, 0);
		// int id = x.buildCanonicalXADD((ArrayList) a.get(0));
		// str = str + "d " + x.getString(id, false) + "\n";

		t.read("( [x1 > 0.0] ( [x1 < 10] ( [0.1] ) ( [0.0] ) ) ( [0.0] ) ) ");
		a = HierarchicalParser.ParseFileInt(t, 0);
		id = x.buildCanonicalXADD((ArrayList) a.get(0));
		id = apply(x, id, .1, XADD.PROD);
		str = str + "x1 " + x.getString(id, false) + "\n";
		ids[0] = id;

		// t.read("( [x1 > d - 3.0] ( [x1 < d + 3.0] ( [ -0.01 * x1 * x1 - 0.01 * d * d + 2.0 * 0.015 * d * x1 + 0.001 * x1 - 0.001 * d + 0.99] ) ( [0.0] ) ) ( [0.0] ) ) ");
		t.read("( [x1 > d - 2.0]( [x1 < d + 2.0]( [0.4 * (-0.2 * x1 * x1 - 0.2 * d * d + 2.0 * 0.2 * d * x1 + 0.01 * x1 - 0.01 * d + 0.9)] )	( [0.0] ) )	( [0.0] ) ) ");
		a = HierarchicalParser.ParseFileInt(t, 0);
		id = x.buildCanonicalXADD((ArrayList) a.get(0));
		id = apply(x, id, .92, XADD.PROD);
		str = str + "x1 " + x.getString(id, false) + "\n";
		ids[1] = id;

		// d + 3.0
		t.read("( [x1 > 9.0] ( [x1 < 10] ( [(0.1 * (x1 - 0.1))] ) ( [0.0] ) ) ( [0.0] ) ) ");
		a = HierarchicalParser.ParseFileInt(t, 0);
		id = x.buildCanonicalXADD((ArrayList) a.get(0));
		id = apply(x, id, .1, XADD.PROD);
		str = str + "x1 " + x.getString(id, false) + "\n";
		ids[2] = id;

		// System.out.println(str);

		id = apply(x, ids, XADD.SUM);
		write(x.getString(id, false), count);
		// System.out.println(x.getString(id, false)); // id
	}

	protected static void write(String str, int count) {
		StringBuilder s = new StringBuilder(
				"bvariables ( ) \n	case test\n	 d ( [d > 0.0] ([d < 10] ( [0.1] ) ( [0] ) ) ( [0] ) )\n ");

		s.append(" x1 " + str);
		for (int i = 2; i <= count; i++) {
			s.append("\n x" + i + str.replace("x1", "x" + i));
		}

		Utils.print("./src/sve/Robotics.sve", s.append("\nendcase").toString());
	}

	static int apply(XADD x, int[] ids, int op) {
		int t = ids[0];
		for (int i = 1; i < ids.length; i++) {
			t = x.apply(t, ids[i], op);
		}

		return t;
	}

	static int apply(XADD x, int id, double val, int op) {
		// ArrayList a = ;
		id = x.apply(id, SVE.getSingleXADD(x, Double.toString(val)), op);
		return id;
	}
}
